import { ApiRequest } from "./ApiRequest";
import { ApiResponse } from './ApiResponse';

class ApiService {
  private socket: WebSocket | null = null;

  public async scanServer(callback: (result: string) => void): Promise<void> {
    const ipRanges = ['192.168.1.', '192.168.2.'];
    const port = 13301;
    const max = 254;
    const queue: string[] = [];
    const concurrencyLimit = 100;

    // 填充队列
    ipRanges.forEach(ipRange => {
      for (let i = 1; i <= max; i++) {
        queue.push(`ws://${ipRange}${i}:${port}/ws`);
      }
    });

    // 并发控制函数
    const processQueue = async () => {
      while (queue.length > 0) {
        const url = queue.shift()!;
        await connectToServer(url);
      }
    };

    // 处理单个连接
    const connectToServer = async (url: string): Promise<void> => {
      return new Promise((resolve) => {
        const ws = new WebSocket(url);

        ws.onopen = () => {
          console.log(`WebSocket connection opened to ${url}`);
          callback(url);
          ws.close();
          resolve();
        }

        ws.onerror = () => {
          console.log(`No response from server at ${url}`);
          resolve(); // 确保在错误时也释放并发槽位
        }
      });
    };

    // 启动并发控制
    const promises = Array.from({ length: concurrencyLimit }, () => processQueue());
    await Promise.all(promises);
  }

  public connect(url: string): Promise<boolean> {
    return new Promise((resolve, reject) => {
      if (this.socket) {
        console.log('WebSocket already connected');
        resolve(true);
        return;
      }

      this.socket = new WebSocket(url);

      this.socket.onopen = () => {
        console.log('WebSocket connection opened');
        resolve(true);
      };

      this.socket.onmessage = (event: MessageEvent) => {
        const res: ApiResponse = JSON.parse(event.data);
        this.handleMessage(res);
      };

      this.socket.onclose = () => {
        console.log('WebSocket connection closed');
        this.socket = null;
        resolve(false); // 连接关闭时返回 false
      };

      this.socket.onerror = (error: Event) => {
        console.error(`WebSocket error: ${error}`);
        reject(error);
      };
    });
  }

  public disconnect(): void {
    if (this.socket) {
      this.socket.close();
      this.socket = null;
    }
  }

  public checkStatus(): boolean {
    return this.socket !== null;
  }

  public login(callback: (response: ApiResponse) => void) {
    const request: ApiRequest = {
      action: "login"
    };
    this.sendSync(request, callback);
  }

  public sendSync(request: ApiRequest, callback: (response: ApiResponse) => void, timeout: number = 10000): void {
    if (!this.socket || this.socket.readyState !== WebSocket.OPEN) {
      // 不再在这里处理错误提示
      return;
    }

    const message = JSON.stringify(request);
    this.socket.send(message);

    let timeoutId: ReturnType<typeof setTimeout> | null = null;

    const listener = (event: MessageEvent) => {
      const response: ApiResponse = JSON.parse(event.data);
      callback(response);
      if (timeoutId) {
        clearTimeout(timeoutId);
      }
      if (this.socket) {
        this.socket.removeEventListener('message', listener);
      }
    };

    this.socket.addEventListener('message', listener);

    timeoutId = setTimeout(() => {
      this.disconnect();
      if (this.socket) {
        this.socket.removeEventListener('message', listener);
      }
    }, timeout);
  }

  public send(request: ApiRequest): void {
    if (!this.socket || this.socket.readyState !== WebSocket.OPEN) {
      // 不再在这里处理错误提示
      return;
    }

    const message = JSON.stringify(request);
    this.socket.send(message);
  }

  private handleMessage(res: ApiResponse) {
    switch (res.callback) {
      default:
        console.log('Received message:', res);
    }
  }
}

export default new ApiService();